#!/bin/bash
# $Id$


# edit descriptors
# XXX validate descriptors
# optionaly add authorized_keys 
# targz it

__get_desc_val ()
{
	echo "$(< $1 )" | grep "^${2}=" | cut -f2 -d"=" | sed -e 's/"//g' 2>/dev/null
}

__strip_bdot ()
{
	n="`echo $1|cut -f2 -d"."`"	
	echo $n
}

__strip_adot ()
{
	n="`echo $1|cut -f1 -d"."`"	
	echo $n
}

edit () {

	local ans s

	for s in TIME MISC NETWORK SERVICES BOOT PACKAGES netinstall/NETWORK AUTOINSTALL; do
		unset ans
		echo -ne "\n Wish to edit the descriptor: $s ? [y/n]: "
		read ans
		if [ "$ans" = "y" -o "$ans" = "Y" ]; then
			vi $nemodir/$s
		else
			continue
		fi
	done
}

edit_disks () {

	local ans d edited cntans

	echo -e "\nEnter the name of the disk related descritors to edit separated by a space. Or type "none" to skip.\n"
	echo " Example: DISK.hdb DISK.sdc MD.md2 ENCLAYER.root LVM.vgroot MOUNTPOINT.boot .. " 
	echo -n "Descriptor: "

	read ans
	if [ "$ans" = "none" ]; then
		return
	fi

	for d in $ans ; do
		echo " Descriptors edited: $edited "
		sleep 1
		dn="`__strip_bdot $d`" # name
		ds="`__strip_adot $d`" # DESC
		[ "$dn" = "tmp" -o "$dn" = "bck" ] && _err_msg " Can have 'tmp' or 'bck' as a name "
		if [ ! -f $nemodir/$d ]; then
			cp -v $nemodir/files/`echo $ds|tr '[:upper:]' '[:lower:]'`/${ds}.template \
				$nemodir/${d}
		fi
		echo "Type any key to continue ..."
		read cntans
		vi $nemodir/${d}
		# sfdisk
		if [ "$ds" = "DISK" ]; then
			if [ ! -f $nemodir/sfdisk.${dn} ]; then
				cp -v $nemodir/files/disk/sfdisk.template $nemodir/sfdisk.${dn}
				echo "Type any key to continue ..."
				read cntans
			fi
			vi $nemodir/sfdisk.${dn}
		fi
		edited="$edited $d"
	done
	
}

# main
if [ $# -lt 2 ]; then
		echo -e "\nERROR: Usage: 1:{ edit | edit_disks } 2:{ directory }\n"
		echo -e "	edit	Edits TIME NETWORK SERVICES BOOT PACKAGES"
		echo -e "	edit_disks	Edits DISK MD ENCLAYER LVM MOUNTPOINT\n"
		exit 1
fi

cmd=$1
nemodir=$2
wd="`pwd`"

echo -e "\n Give me a second ..."

if [ ! -d $nemodir ]; then
	if [ $wd/files/installcd-initrd/nemonico ]; then
		mkdir -p $nemodir
		cp -a $wd/files/installcd-initrd/nemonico/* $nemodir/
	else
		echo -e "\nERROR: Cant find the source tree of nemonico."
		echo -e "\nUntar tools/autoinstall/nemonico_template.tar.gz from the CD into $nemodir."
		exit 1
	fi
fi

$cmd

echo -e "\nCopy the public key to $nemodir/keys and chmod 600 it."
echo -e "Then run: "tar zcf "<HOSTNAME>.tar.gz" -C $nemodir .""

# vim: ts=4
# prepate_autoinstall.sh: end
